/**
 * @description: 这是Eirudy创建的类~
 * @author: Eirudy
 * @hope: 憧憬成为java大师
 **/

package org.eirudy.shareimage.manager.upload;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpStatus;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import org.eirudy.shareimage.exception.BusinessException;
import org.eirudy.shareimage.exception.ErrorCode;
import org.eirudy.shareimage.exception.ThrowUtils;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.List;

@Service
public class UrlPictureUpload extends PictureUploadTemplate {

    private String contentType = "png";

    final List<String> TYPE = Arrays.asList("jpg", "jpeg", "png", "webp");

    @Override
    protected void validPicture(Object inputSource) {
        String url = (String) inputSource;
        // 校验Url 是否为空
        ThrowUtils.throwIf(StrUtil.isBlank(url), ErrorCode.PARAMS_ERROR,"参数为空");
        // 校验文件格式
        try{
            new URL(url);
        }catch (MalformedURLException e){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件地址格式不正确");
        }

        //校验协议
        ThrowUtils.throwIf(!(url.startsWith("http://") || url.startsWith("https://")),ErrorCode.PARAMS_ERROR,"仅支持http和https");

        //校验文件存在性，发送head请求
        HttpResponse response = null;
        try {
            response = HttpUtil.createRequest(Method.HEAD, url).execute();
            if (response.getStatus() != HttpStatus.HTTP_OK) {
                return;
            }

            //校验文件类型
            String type = response.header("Content-Type");
            if (StrUtil.isNotBlank(type)) {
                final List<String> ALLOW_CONTENT_TYPE = Arrays.asList("image/jpg", "image/jpeg", "image/png", "image/webp");
                ThrowUtils.throwIf(!ALLOW_CONTENT_TYPE.contains(type.toLowerCase()),
                        ErrorCode.PARAMS_ERROR,"文件类型错误");
                contentType =type.substring(type.lastIndexOf("/") + 1);
            }


            //校验文件大小
            String contentLength = response.header("Content-Length");
            if (StrUtil.isNotBlank(contentLength)) {
                try {
                    Long currentSize = Long.parseLong(contentLength);
                    Long ONE_M = 1024 * 1024L;
                    ThrowUtils.throwIf(currentSize > 2*ONE_M,ErrorCode.PARAMS_ERROR,"文件大小格式异常");
                } catch (NumberFormatException e) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR,"文件大小格式异常");
                }

            }
        }finally {
            if (response != null) {
                response.close();
            }
        }
    }

    /**
     *
     * @param inputSource
     * @return
     */
    @Override
    protected String getOriginFilename(Object inputSource) {
        String url = (String) inputSource;
        url = FileUtil.getName(url);
        String suffix = FileUtil.getSuffix(url);
        if(!TYPE.contains(suffix.toLowerCase())){
            url = url.substring(0,url.lastIndexOf('.')+1)+contentType;
        }
        return url;
    }

    @Override
    protected void processFile(Object inputSource, File file) throws Exception {
        String url = (String) inputSource;
        HttpUtil.downloadFile(url,file);
    }


}
